package cn.afactory.tygz.ui.base.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import cn.afactory.tygz.R;
import cn.afactory.tygz.controller.SearchController;
import cn.afactory.tygz.ui.activities.TopicAddActivity;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.utils.NoLeakHandler;
import cn.afactory.tygz.ui.base.utils.StringUtils;
import cn.afactory.tygz.ui.base.utils.ToastUtils;
import cn.afactory.tygz.ui.base.utils.ViewUtils;
import cn.afactory.tygz.ui.base.views.search.ISearch;
import cn.afactory.tygz.ui.base.views.search.SearchMainFragment;
import cn.afactory.tygz.ui.base.views.search.SearchSourcePager;
import cn.afactory.tygz.ui.base.views.search.SearchType;
import cn.afactory.tygz.ui.base.views.search.SearchView;
import cn.afactory.tygz.ui.fragments.SearchResultCompanyListFragment;
import cn.afactory.tygz.ui.fragments.SearchResultTopicListFragment;

/**
 * Created by Kenneth on 15/9/9.
 */
public class SearchActivity extends BaseActivity implements NoLeakHandler.HandlerCallback {

    public static final String KEY_SEARCH_PAGE = "search_page";
    public static final String KEY_SEARCH_KEY = "search_key";
    private SearchType mSearchType = SearchType.COMPANY;
    private SearchSourcePager mSearchSourcePager;
    private SearchMainFragment mMainFragment;
    private SearchView mSearchView;
    private SearchController mController;
    private NoLeakHandler mUiHandler;
    private View mEmptyView;
    private ViewGroup mViewContainer;
    private TextView mEmptyTips;
    private TextView mCreateTips;

    private String mSearchKey;

    @Override
    public void handleMessage(Message msg) {
//        switch (msg.what) {
//            case SearchController.MSG_KEY_THINK_WORD_LIST:
//                if (msg.obj instanceof List<?>) {
//                    onThinkWordListLoaded((List<LoganThinkWordEntity>) msg.obj);
//                }
//                break;
//        }
//        hideLoadingDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addTitleBar = false;
        setContentView(R.layout.activity_search_layout);
        initIntent();
        initViews();
        setMainFragment();
        mUiHandler = new NoLeakHandler(this);
        mController = new SearchController(this, mUiHandler);
    }

    public static Intent createIntent(Context context, SearchSourcePager page) {
        Intent intent = new Intent(context, SearchActivity.class);
        Bundle data = new Bundle();
        data.putInt(KEY_SEARCH_PAGE, page.getId());
        intent.putExtras(data);
        return intent;
    }

    /**
     * 从intent中初始数据
     */
    private void initIntent() {
        int type = getIntent().getIntExtra(KEY_SEARCH_PAGE, 0);
        if (SearchSourcePager.COMPANY.getId() == type) {
            mSearchType = SearchType.COMPANY;
            mSearchSourcePager = SearchSourcePager.COMPANY;
        } else {
            mSearchType = SearchType.TOPIC;
            mSearchSourcePager = SearchSourcePager.TOPIC;
        }
    }

    /**
     * 初始化view
     */
    private void initViews() {
        mSearchView = (SearchView) findViewById(R.id.search_view_title);
        mSearchView.setOnSearchViewClickListener(mSearchViewListener);
        mSearchView.setSearchType(mSearchSourcePager, mSearchType);

        mViewContainer = ViewUtils.findView(this, R.id.search_fragment_container);
        mEmptyView = ViewUtils.findView(this, R.id.empty_view);
        mEmptyTips = ViewUtils.findView(this, R.id.search_empty_title);
        mCreateTips = ViewUtils.findView(this, R.id.create_topic);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    /**
     * 设置搜索主页
     */
    private void setMainFragment() {
        mMainFragment = SearchMainFragment.newInstance();
        mMainFragment.setSearchPagerAndType(mSearchSourcePager, mSearchType);
        updateFragment(mMainFragment);
    }

    /**
     * 更新结果页面
     */
    private void onSearchResultFragment() {
        Fragment fragment = ResultFragmentFactory.createBy(mSearchSourcePager, mSearchType, mSearchKey);
        updateFragment(fragment);
    }

    /**
     * @param fragment
     */
    private void updateFragment(Fragment fragment) {
        showEmptyView(false);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.search_fragment_container, fragment);
        ft.commitAllowingStateLoss();

    }

    /**
     * 搜索 view的监听事件
     */
    private SearchView.OnSearchViewClickListener mSearchViewListener = new SearchView.
            OnSearchViewClickListener() {
        @Override
        public void onSearchTypeChange(SearchType searchType, String content) {

        }

        @Override
        public void onContentChange(SearchType searchType, String content) {
            onSearchContentChange(content);
        }

        @Override
        public void onClearContent() {

        }

        @Override
        public void onStartSearch(SearchType searchType, String content) {
            startSearch(searchType, content);
        }

        @Override
        public void onCancelSearch() {
            finish();
        }
    };

    /**
     * 搜索内容变动
     *
     * @param content
     */
    private void onSearchContentChange(String content) {
        if (content.length() > 0) {

        } else {
            setMainFragment();
        }
    }

    /**
     * 开始搜索请求
     *
     * @param type
     * @param content
     */
    public void startSearch(SearchType type, String content) {
        if (TextUtils.isEmpty(content)) {
            ToastUtils.show(this, R.string.search_key_empty);
            return;
        }

        hideInputMethod(mSearchView);

        mSearchKey = content;
        mSearchView.setSearchContent(content, false);
        onSearchResultFragment();

        showEmptyView(false);
//        onNothingSearched();
    }

    private void showEmptyView(boolean show) {
        if (show) {
            mEmptyView.setVisibility(View.VISIBLE);
            mViewContainer.setVisibility(View.GONE);
        } else {
            mEmptyView.setVisibility(View.GONE);
            mViewContainer.setVisibility(View.VISIBLE);
        }

    }

    private boolean isEmptyVisible() {
        return View.VISIBLE == mEmptyView.getVisibility() ? true : false;
    }

    /**
     * 没有搜索到任务东西
     */
    public void onNoCompanySearched() {
        showEmptyView(true);
        String orgStr = getString(R.string.comsearch_result_empty_tips, mSearchKey);
        String createStr = getString(R.string.search_create_tips, mSearchKey);
        mEmptyTips.setText(StringUtils.replaceAll(orgStr, mSearchKey, getResources().
                getColor(R.color.font_sub_ff6666)));
        mCreateTips.setVisibility(View.GONE);
    }

    /**
     * 没有搜索到任务东西
     */
    public void onNothingSearched() {
        showEmptyView(true);
        String orgStr = getString(R.string.topicsearch_result_empty_tips, mSearchKey);
        String createStr = getString(R.string.search_create_tips, mSearchKey);
        mEmptyTips.setText(StringUtils.replaceAll(orgStr, mSearchKey, getResources().
                getColor(R.color.font_sub_ff6666)));
        mCreateTips.setText(StringUtils.replaceAll(createStr, mSearchKey, getResources().
                getColor(R.color.white)));
        mCreateTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, TopicAddActivity.class);
                intent.putExtra(TopicAddActivity.EXT_DATA_TAG, mSearchKey);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUiHandler.setValid(false);
    }

    private static class ResultFragmentFactory {
        public static Fragment createBy(SearchSourcePager sourcePager,
                                        SearchType searchType,
                                        String searchContent) {
            Fragment fragment = null;
            switch (searchType) {
                case COMPANY:
                    fragment = new SearchResultCompanyListFragment();
                    break;
                case TOPIC:
                    fragment = new SearchResultTopicListFragment();
                    break;
                default:
                    fragment = new SearchResultTopicListFragment();
                    break;
            }

            if (fragment instanceof ISearch) {
                ((ISearch) fragment).onSearch(sourcePager, searchType, searchContent);
            }
            return fragment;
        }
    }
}
